package top.iuna.jxls.core.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import top.iuna.jxls.core.model.AIPaddler;
import top.iuna.jxls.core.model.PaddlerRanking;

/**
 * 国际乒联运动员排名Service
 * 
 * @author Cheney.Sun
 * @time 2018-04-07
 */
@Slf4j
@Service
public class PaddlerRankingService {

  /**
   * 2018年4月男子世界排名前10
   */
  public List<PaddlerRanking> getMenRankingList() {
    return getDataFromJsonFile("static/men-ranking-201804-10-list.json");
  }

  /**
   * 2018年4月女子世界排名前20
   */
  public List<PaddlerRanking> getWomenRankingList() {
    return getDataFromJsonFile("static/women-ranking-201804-20-list.json");
  }

  /**
   * new一组AI乒乓球运动员
   */
  public List<AIPaddler> newAIPaddlers(int nums) {
    List<AIPaddler> list = new ArrayList<>();
    for (int i = 0, j = nums; i < j; i++) {
      list.add(AIPaddler.create());
    }

    return list;
  }

  /**
   * 从classpath下的json文件中读取PaddlerRanking数据
   */
  private List<PaddlerRanking> getDataFromJsonFile(String classpathSourceFilePath) {
    if (StringUtils.isEmpty(classpathSourceFilePath)) {
      return Collections.emptyList();
    }

    String fileToString = null;
    try {
      fileToString = FileUtils.readFileToString(ResourceUtils.getFile("classpath:" + classpathSourceFilePath), "UTF-8");
    } catch (IOException e) {
      log.error("PaddlerRankingService#getDataFromJsonFile error:", e);
    }

    return StringUtils.isNotEmpty(fileToString) ? JSON.parseArray(fileToString, PaddlerRanking.class)
        : Collections.emptyList();
  }


}
